﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using NetworkSerialPort.Helper.TcpSocket;
using oModbus.Utility;
using Sample.Helper;

namespace NetworkSerialPort
{
    public class NetworkSerialService
    {
        /// <summary>
        /// tcp 服务
        /// </summary>
        private TcpService _server;
        private Dictionary<IDataTransmit, string> _seesion = new Dictionary<IDataTransmit, string>();
        /// <summary>
        /// 日志管理器
        /// </summary>
        protected readonly ILog LogManager;
        /// <summary>
        /// 日志事件
        /// </summary>
        public event Action<string, string> LogEvent;
        protected virtual void Log(string title, string message)
        {
            LogManager?.Info(title, message);
            LogEvent?.Invoke(title, message);
        }
        /// <summary>
        /// 开始监听
        /// </summary>
        public void Start()
        {
            _server.Start();
        }

        /// <summary>
        /// 停止监听
        /// </summary>
        public void Stop()
        {
            if (_server != null)
            {
                _server.Close();
                _server = null;
            }
        }
        /// <summary>
        /// 构造方法
        /// </summary> 
        /// <param name="port"></param>
        /// <param name="log"></param>
        public NetworkSerialService(int port, ILog log = null)
        {
            LogManager = log;
            //在指定端口上建立监听线程
            _server = new TcpService(port);
            _server.Connected += _server_Connected;
            _server.DisConnect += _server_DisConnect;
        }

        private void _server_DisConnect(IDataTransmit sender, NetEventArgs e)
        {
            if (_seesion.ContainsKey(sender))
            {
                _seesion.Remove(sender);
            }

        }

        private void _server_Connected(IDataTransmit sender, NetEventArgs e)
        {
            try
            {
                sender.ReceiveData += ReceiveData;
                //接收数据
                sender.Start();
                if (!_seesion.ContainsKey(sender))
                {
                    _seesion.Remove(sender);
                }
                _seesion.Add(sender, "");
                Log(sender.RemoteEndPoint + " 连接成功", null);

            }
            catch (Exception ex)
            {
                LogManager?.Error(ex);
            }
        }

        /// <summary>
        /// 接收消息 处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ReceiveData(IDataTransmit sender, NetEventArgs e)
        {
            byte[] data = (byte[])e.EventArg;
            Log("接受" + sender.RemoteEndPoint + "数据", data.GetHexString());
        }

        public void SendAll(byte[] data)
        {
            try
            {
                foreach (var item in _seesion)
                {
                    item.Key.Send(data);
                }
            }
            catch (Exception ex)
            {
                LogManager.Error(ex);
            }
        }
    }
}
